package com.whccb.apps.office.document.event.receive;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListener;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListenerInterface;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.HistoryTaskInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.TaskInstance;
import com.actionsoft.bpms.commons.database.RowMapper;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.whccb.apps.office.document.ODConstant;
import com.whccb.apps.office.document.util.ODAppUtil;

/**
 * 
 * 收文流程行长审批后，将审批记录同步至子流程，并发送通知
 * 
 * @author xqli
 * 
 */
public class BankleaderOpinionToSubProcessAndNotifyEvent extends ExecuteListener
        implements ExecuteListenerInterface {
    public String getDescription() {
        return "收文流程行长审批后，先将留言写到行领导意见框，再将签批意见同步至子流程，并发送通知.";
    }

    public String getProvider() {
        return "ActionSoft";
    }

    public String getVersion() {
        return "AWS 6.0";
    }

    @Override
    public void execute(ProcessExecutionContext pec) throws Exception {
        String parentBindid = pec.getProcessInstance().getId();
        List<ProcessInstance> subProcessList = SDK.getProcessAPI().query()
                .parentProcessInstId(pec.getProcessInstance().getId()).list();
        String boName = "BO_WHBK_OD_RECEIVE";
        BO parentBo = SDK.getBOAPI().getByProcess(boName, parentBindid);
        String processInstId = pec.getProcessInstance().getId();
        String taskMsg = "";
        String createTime = "";
        List<Map<String, String>> checkList = getCheckList(processInstId,
                pec.getTaskInstance().getId(), pec.getUserContext().getUID());
        if (checkList != null && !checkList.isEmpty() && checkList.size() > 0) {
            Map<String, String> checkMap = checkList.get(0);
            if (checkMap != null && !checkMap.isEmpty()) {
                taskMsg = checkMap.get("MSG");
                String createDateTime = checkMap.get("CREATEDATE");
                if (StringUtils.isNotEmpty(createDateTime)
                        && createDateTime.contains(".")) {
                    createTime = createDateTime.substring(0,
                            createDateTime.lastIndexOf("."));
                }
            }

        }
        if (taskMsg != null && StringUtils.isNotEmpty(taskMsg.trim())) {
            String taskDefId = pec.getTaskInstance().getActivityDefId();
            Properties odMappingProperties = ODAppUtil
                    .getProperties("SW_TASK_FORM_MAPPING.properties");
            String valueStr = getPropertiesValue(odMappingProperties,
                    taskDefId);
            if (valueStr != null && StringUtils.isNotEmpty(valueStr)) {
                String[] values = valueStr.split("&");
                if (values != null && values.length > 1) {
                    String fieldName = values[0];
                    String checkOption = values[1];
                    if (checkOption != null
                            && StringUtils.isNotEmpty(checkOption)) {
                        if (pec.isChoiceActionMenu(checkOption)) {
                            if (fieldName != null
                                    && StringUtils.isNotEmpty(fieldName)) {
                                String oldValue = SDK
                                        .getBOAPI().getByProcess(boName,
                                                processInstId, fieldName)
                                        .toString();
                                // 如果是退回的，则忽略原先意见
                                List<HistoryTaskInstance> taskHisList = SDK
                                        .getHistoryTaskQueryAPI()
                                        .processInstId(processInstId)
                                        .activityDefId(taskDefId)
                                        .addQuery("TASKSTATE !=", "9")
                                        .addQuery("ID !=",
                                                pec.getTaskInstance().getId())
                                        .target(pec.getUserContext().getUID())
                                        .list();
                                if (taskHisList != null
                                        && !taskHisList.isEmpty()
                                        && taskHisList.size() > 0) {
                                    oldValue = "";
                                }
                                String rightTaskMsg = getTaskMsg(
                                        pec.getUserContext(), oldValue, taskMsg,
                                        createTime);
                                if (rightTaskMsg != null && StringUtils
                                        .isNotEmpty(rightTaskMsg)) {
                                    SDK.getBOAPI().updateByBindId(boName,
                                            processInstId, fieldName,
                                            rightTaskMsg);
                                    // 查询该实例的其他参与者，发送通知
                                    List<TaskInstance> list1 = SDK
                                            .getTaskQueryAPI()
                                            .processInstId(processInstId)
                                            .activityDefId(taskDefId)
                                            .addQuery("TASKSTATE !=", "9")
                                            .addQuery("ID !=",
                                                    pec.getTaskInstance()
                                                            .getId())
                                            .addQuery("TARGET !=", pec
                                                    .getUserContext().getUID())
                                            .list();
                                    List<HistoryTaskInstance> list2 = SDK
                                            .getHistoryTaskQueryAPI()
                                            .processInstId(processInstId)
                                            .activityDefId(taskDefId)
                                            .addQuery("TASKSTATE !=", "9")
                                            .addQuery("ID !=",
                                                    pec.getTaskInstance()
                                                            .getId())
                                            .addQuery("TARGET !=", pec
                                                    .getUserContext().getUID())
                                            .list();
                                    List<String> noticeUserList = new ArrayList<String>();
                                    if (list1 != null && !list1.isEmpty()
                                            && list1.size() > 0) {
                                        for (TaskInstance taskInst : list1) {
                                            if (taskInst != null) {
                                                String uid = taskInst
                                                        .getTarget();
                                                if (!noticeUserList
                                                        .contains(uid + "")) {
                                                    noticeUserList.add(uid);
                                                }
                                            }
                                        }
                                    }
                                    if (list2 != null && !list2.isEmpty()
                                            && list2.size() > 0) {
                                        for (HistoryTaskInstance taskInst : list2) {
                                            if (taskInst != null) {
                                                String uid = taskInst
                                                        .getTarget();
                                                if (!noticeUserList
                                                        .contains(uid + "")) {
                                                    noticeUserList.add(uid);
                                                }
                                            }
                                        }
                                    }
                                    if (noticeUserList != null
                                            && !noticeUserList.isEmpty()
                                            && noticeUserList.size() > 0) {
                                        for (String uid : noticeUserList) {
                                            sendComNotify(parentBo,
                                                    pec.getUserContext()
                                                            .getUserName(),
                                                    processInstId,
                                                    pec.getTaskInstance()
                                                            .getId(),
                                                    uid);
                                        }
                                    }

                                    // 更新子流程，并发送通知
                                    if (subProcessList != null
                                            && !subProcessList.isEmpty()
                                            && subProcessList.size() > 0) {
                                        for (ProcessInstance subProcess : subProcessList) {
                                            if (subProcess != null) {
                                                BO subBo = SDK.getBOAPI()
                                                        .getByProcess(
                                                                "BO_WHBK_OD_RECEIVE_DO",
                                                                subProcess
                                                                        .getId());
                                                if (subBo != null) {
                                                    SDK.getBOAPI()
                                                            .updateByBindId(
                                                                    "BO_WHBK_OD_RECEIVE_DO",
                                                                    subProcess
                                                                            .getId(),
                                                                    fieldName,
                                                                    rightTaskMsg);
                                                    sendNotify(
                                                            subProcess.getId(),
                                                            parentBo,
                                                            pec.getUserContext()
                                                                    .getUserName());
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
    }

    private void sendNotify(String subBinid, BO swBo, String userName) {
        if (StringUtils.isNotEmpty(subBinid) && swBo != null) {
            // 得到子流程的第一节点办理人，即为任务提醒人
            String notifyUserid = "";
            String subTaskId = "";
            List<TaskInstance> taskList = SDK.getTaskAPI().query()
                    .activityDefId(ODConstant.SWBL_TASK_DEFID)
                    .processInstId(subBinid).list();
            if (taskList != null && !taskList.isEmpty()
                    && taskList.size() > 0) {
                notifyUserid = taskList.get(0).getTarget();
                subTaskId = taskList.get(0).getId();
            } else {
                List<HistoryTaskInstance> taskHisList = SDK.getTaskAPI()
                        .queryHistory()
                        .activityDefId(ODConstant.SWBL_TASK_DEFID)
                        .processInstId(subBinid).list();
                if (taskHisList != null && !taskHisList.isEmpty()
                        && taskHisList.size() > 0) {
                    notifyUserid = taskHisList.get(0).getTarget();
                    subTaskId = taskHisList.get(0).getId();
                }
            }
            sendComNotify(swBo, userName, subBinid, subTaskId, notifyUserid);
            // // 发送通知
            // JSONObject json = new JSONObject();
            // StringBuffer notifycontent = new StringBuffer();
            // notifycontent.append("来文机构:").append(swBo.getString("RECEIVEORG"))
            // .append(",文号为：").append(swBo.getString("FILENUM"))
            // .append("的收文流程，行领导:" + userName + "有最新的批示，请及时查阅！");
            // json.put("notifycontent", notifycontent.toString());
            // json.put("bindid", subBinid);
            // json.put("taskid", subTaskId);
            // Map<String, Object> params = new HashMap<String, Object>();
            // params.put("sender", "admin");
            // params.put("targetIds", notifyUserid);
            // params.put("content", json.toString());
            // params.put("systemName", ODConstant.NOTIFY_SYSNAME);
            // ODAppUtil.sendOfficeDocumentNotification(params);
        }
    }

    private void sendComNotify(BO swBo, String userName, String bindid,
            String taskid, String notifyUserid) {
        // 发送通知
        // JSONObject json = new JSONObject();
        StringBuffer notifycontent = new StringBuffer();
        notifycontent.append("来文机构:").append(swBo.getString("RECEIVEORG"))
                .append(",文号为：").append(swBo.getString("FILENUM"))
                .append("的收文流程，行领导:" + userName + "有最新的批示，请及时查阅！");
        // json.put("notifycontent", notifycontent.toString());
        // json.put("bindid", bindid);
        // json.put("taskid", taskid);
        // Map<String, Object> params = new HashMap<String, Object>();
        // params.put("sender", "admin");
        // params.put("targetIds", notifyUserid);
        // params.put("content", json.toString());
        // params.put("systemName", ODConstant.NOTIFY_SYSNAME);
        SDK.getTaskAPI().createUserNotifyTaskInstance(bindid, taskid, "admin",
                notifyUserid, notifycontent.toString());
        // ODAppUtil.sendOfficeDocumentNotification(params);
    }

    private List<Map<String, String>> getCheckList(String bindid, String taskid,
            String uid) {
        String querySql = " SELECT a.CREATEUSER,a.CREATEDATE,a.ACTIONNAME,a.MSG FROM WFC_COMMENT a WHERE a.PROCESSINSTID = :PROCESSINSTID AND a.TASKINSTID = :TASKINSTID AND a.CREATEUSER = :CREATEUSER";
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("PROCESSINSTID", bindid);
        paramMap.put("TASKINSTID", taskid);
        paramMap.put("CREATEUSER", uid);
        return DBSql.query(querySql, paramMap,
                new RowMapper<Map<String, String>>() {
                    public Map<String, String> mapRow(ResultSet rs, int index)
                            throws SQLException {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("CREATEUSER", rs.getString("CREATEUSER"));
                        map.put("CREATEDATE", rs.getString("CREATEDATE"));
                        map.put("ACTIONNAME", rs.getString("ACTIONNAME"));
                        map.put("MSG", rs.getString("MSG"));
                        return map;
                    }

                });
    }

    private String getPropertiesValue(Properties pro, String name) {
        String value = "";
        if (pro != null && !pro.isEmpty()) {
            try {
                value = pro.getProperty(name);
            } catch (Exception e) {

            }
        }
        return value;
    }

    private String getTaskMsg(UserContext me, String oldValue, String msg,
            String createTime) {
        StringBuffer result = new StringBuffer();
        if (oldValue != null && StringUtils.isNotEmpty(oldValue)) {
            result.append(oldValue);
            result.append("\r\n").append("\r\n");
        }
        String userName = me.getUserName();
        if (StringUtils.isNotEmpty(msg)) {
            result.append(msg);
            result.append("\r\n");
            result.append("                   ").append(userName).append(" ")
                    .append(createTime);
        }
        return result.toString();
    }
}
